package com.borrowed.book.book.controller;

import com.borrowed.book.book.domain.WeiCreateOrderInDto;
import com.borrowed.book.book.domain.WeiRefundInDto;
import com.borrowed.book.system.domain.AjaxResult;
import com.borrowed.book.weixin.service.WxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Api(tags = "微信支付")
@RestController
@RequestMapping("/api/weipay")
public class WeiChatPayController {
    @Autowired
    private WxPayService wxPayService;

    @ApiOperation(value = "订单预准备",httpMethod = "POST")
    @PostMapping("/createOrder")
    @ResponseBody
    @Transactional
    public AjaxResult createOrder(@RequestBody WeiCreateOrderInDto param) {
        try {
            Map<String, Object> resultMap = wxPayService.PayTransaction(param.getTotal(), param.getOrderNo());
            return AjaxResult.sucess("操作成功", resultMap);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "支付通知",httpMethod = "POST")
    @PostMapping("/notify")
    @ResponseBody
    @Transactional
    public AjaxResult notify(HttpServletRequest request, HttpServletResponse response){
        try {
            String result=wxPayService.PayNotifyResult(request, response);
            return AjaxResult.sucess(result);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "申请退款",httpMethod = "POST")
    @PostMapping("/refund")
    @ResponseBody
    @Transactional
    public AjaxResult refund(@RequestBody WeiRefundInDto param){
        try {
            Map<String, Object> resultMap=wxPayService.PayRefund(param.getRefund(), param.getOrderNo(),param.getReason());
            return AjaxResult.sucess("操作成功",resultMap);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "退款通知",httpMethod = "POST")
    @PostMapping("/refundNotify")
    @ResponseBody
    @Transactional
    public AjaxResult refundNotify(HttpServletRequest request, HttpServletResponse response){
        try {
            String result=wxPayService.PayRefundNotify(request, response);
            return AjaxResult.sucess(result);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }
}
